package com.xhtt.smart.card.client.handle;

import com.alibaba.fastjson.JSON;
import com.xhtt.smart.card.common.enums.FunctionTypeEnum;
import com.xhtt.smart.card.common.enums.TransferTypeEnum;
import com.xhtt.smart.card.common.msg.bean.MsgClientBean;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wangze
 * @date 2018-07-04 14:28.
 **/
public class ClientHandle extends SimpleChannelInboundHandler<MsgClientBean> {
    private final static Logger LOGGER = LoggerFactory.getLogger(ClientHandle.class);


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;

            if (idleStateEvent.state() == IdleState.WRITER_IDLE) {
                LOGGER.info("已经 10 秒没有发送信息！");
                //向服务端发送消息

                MsgClientBean msg = new MsgClientBean();
                msg.setTransferType(TransferTypeEnum.UP);

                byte[] bytes = {1, 2, 3};
                msg.setFunctionType(FunctionTypeEnum.HEART_UP);
                msg.setDataLength(3);
                msg.setData(bytes);
                ctx.writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }


        }

        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        //客户端和服务端建立连接时调用
        LOGGER.info("已经建立了联系。。");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MsgClientBean msg) throws Exception {

        if (msg != null) {
            //从服务端收到消息时被调用
            LOGGER.info("客户端收到消息={}", JSON.toJSONString(msg));
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //异常时断开连接
        cause.printStackTrace();
        ctx.close();
    }
}
